package com.naodong.shenluntiku.mvp.model.data.manager;

import com.naodong.shenluntiku.mvp.model.bean.Token;

import net.orange_box.storebox.StoreBox;

import me.shingohu.man.util.UiUtils;

/**
 * Created by hujie on 17/5/10.
 */

public class TokenManager {

    private Token token;
    private Token.TokenPerferences tokenPerferences;

    private static TokenManager tokenManager;

    public static TokenManager getInstance() {
        if (tokenManager == null) {
            tokenManager = new TokenManager();
        }
        return tokenManager;
    }
    
    private TokenManager() {
        tokenPerferences = StoreBox.create(UiUtils.getContext(), Token.TokenPerferences.class);
    }

    /**
     * 登录并且有效
     * @return
     */
    public boolean hasLoginAndExpires() {
        if (getLocalToken() != null && getLocalToken().isExpires()) {
            return true;
        }
        return false;
    }



    /**
     *
     * @param token
     */
    public void setToken(Token token) {
        this.token = token;
        token.setLoginTn(System.currentTimeMillis());
    }

    /**
     * 保存到本地
     */
    public void saveToken() {
        if (token != null) {
            tokenPerferences.saveToken(token);
        }
    }

    /**
     * 获取访问token
     * @return
     */
    public String getAccessToken() {
        if (getToken() != null) {
            return getToken().getAccessToken();
        }
        return null;
    }



    /**
     * 清除本地缓存
     */
    public void clearToken() {
        if (tokenPerferences != null) {
            tokenPerferences.clear();
        }
        this.token = null;
    }

    public Token getToken() {
        if (token == null) {
            token = getLocalToken();
        }
        return token;
    }

    private Token getLocalToken() {
        if (tokenPerferences != null) {
            return tokenPerferences.getToken();
        }
        return null;
    }
}
